import flash.events.Event;
using Reflect;
class Console extends flash.display.Sprite
{
	var console : fl.controls.TextArea;
	
	public function new()
	{
		super();
		console = new fl.controls.TextArea();
		console.height = 125;
		addChild(console);
		addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
	}
	function onAddedToStage(event:Event):Void
	{
		removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
		stage.addEventListener(Event.RESIZE, onStageResize);
		onStageResize(null);
	}
	function onStageResize(event:Event):Void
	{
		console.width = stage.stageWidth;
	}
	public function log(msg:Dynamic, ?p:haxe.PosInfos)
	{
		console.text+= formatDate(Date.now());
		console.text+= " " + p.fileName +":"+p.lineNumber+":"+p.methodName;
		console.text+= " " + msg+"\n";
		var cls:Dynamic = Type.getClass(msg);
		//console.text+= cls+ "\n";
		if(cls == flash.events.SyncEvent)
		{
			var list:Array<Dynamic> = msg.changeList;
			var idx=0;
			for(obj in list)
			{
				console.text += "\tchangeList[" + idx++ + "] code = " + obj.code;
				if(obj.code=="change")
					 console.text += "\tso.data." + obj.name + "=" + msg.currentTarget.data.field(obj.name);
				if(obj.code=="success")
					 console.text += "\tso.data." + obj.name + "=" + msg.currentTarget.data.field(obj.name);
				console.text += "\n";
			}
		}
		else if(cls == flash.events.NetStatusEvent)
		{
			for(f in msg.info.fields())
					console.text+= "\tinfo." + f + " = " + msg.info.field(f) + "\n";
		}
		else if(cls==flash.events.AsyncErrorEvent)
		{
			//console.text += "target="+event.currentTarget+", error=" + event.error);
		}
		else if(cls==null)
		{
			for(f in msg.fields())
					console.text+= "\tobj." + f + " = " + msg.field(f) + "\n";
		}
		console.textField.scrollV = console.textField.maxScrollV;
	}
	function formatDate(d:Date):String
	{
		var h:Dynamic = d.getHours();
		if(h<10) h="0"+h;
		var m:Dynamic = d.getMinutes();
		if(m<10) m="0"+m;
		return "[" + h + ":" + m + "]";
	}
}